<?php

namespace App\Console\Commands;

use App\Helpers\Utils;
use App\Models\Permission;
use App\Models\PermissionCategory;
use App\Models\Role;
use Illuminate\Console\Command;

class PermissionGenerate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'perm:gen';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'generate permissions and permission_categories data by route and zh-CN/models.php,operation.php file ';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $ex = ['debugbar','api','home','waiting'];
        $app = app();
        $routes = $app->routes->getRoutes();
        $models=[];
        $operations=[];
        $answer = $this->ask('truncate table permissions?','n');
        if(strtolower($answer)=='y'){
            \DB::unprepared('SET FOREIGN_KEY_CHECKS=0;');
            Permission::truncate();
            PermissionCategory::truncate();
        }

        $menu_categories = Utils::get_menus()->toArray();
        foreach ($menu_categories as $name=>$menu_category) {
            $pc = PermissionCategory::firstOrCreate(['name'=>$name],['name'=>$name]);
            foreach ($menu_category as $route=>$display_name) {
                Permission::firstOrCreate(['name'=>$route],['permission_category_id'=>$pc->id,'name'=>$route,'uri'=>'','display_name'=>$display_name]);
            }
        }
        $this->info('重新创建菜单路由完毕');
        foreach ($routes as $k=>$value){
            $action=$value->action;
            try {
                $middleware = $action['middleware'];
                if(is_array($middleware) && in_array('auth',$middleware)){
                    if(array_has($action,'as') && !in_array($action['as'],$ex))
                    {
                        $name = $action['as'];
                        $uri = $value->uri;
                        $names = explode('.',$name);
                        if(count($names)>1){
                            $cn= array_shift($names);
                            $categoryName = trans("model.$cn");

                            if($categoryName=="model.$cn"){
                                $models[$cn]=$cn;
                            }
                            $pc = PermissionCategory::firstOrCreate(['name'=>$categoryName],['name'=>$categoryName]);
                            $op =array_pop($names);
                            $operation = trans('operation.'.$op);

                            if($operation=='operation.'.$op){
                                $operations[$op]=$op;
                            }
                            $item = $categoryName.$operation;
                            Permission::firstOrCreate(['name'=>$name],['permission_category_id'=>$pc->id,'name'=>$name,'uri'=>$uri,'display_name'=>$item]);
                        }
                    }
                };
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }
        }
        $this->info('重新按路由创建权限项完毕');

        if(count($models)){
            $this->warn('please add mapping to zh-CN/model.php');
            foreach ($models as $k=>$v){
                $this->info("'$k'=>'$v',");
            }
        }


        if(count($operations)){
            $this->warn('please add mapping to zh-CN/operation.php');
            foreach ($operations as $k=>$v){
                $this->info("'$k'=>'$v',");
            }
        }


        $this->info('重新分配权限');
        $cats = PermissionCategory::all();

        $admin_except = ['用户','角色','权限','权限类型','用户管理'];
        $admin_perm_cats = $cats->filter(function ($v)use($admin_except){
            return in_array($v->name,$admin_except)==false;
        });
        $admin_perm_ids = $admin_perm_cats->map(function($cat){
            return $cat->permissions->pluck('id');
        })->flatten()->all();

        $role_admin = Role::query()->where('name','管理员')->first();

        if($role_admin){
            $role_admin->perms()->sync($admin_perm_ids);

            $op_except = ['用户','角色','权限','权限类型','用户管理','基础数据'];
            $op_perm_cats = $cats->filter(function ($v)use($op_except){
                return in_array($v->name,$op_except)==false;
            });
            $op_perm_ids = $op_perm_cats->map(function($cat){
                return $cat->permissions->pluck('id');
            })->flatten()->all();
        }

        $role_op = Role::query()->where('name','操作员')->first();
        if($role_op){
            $role_op->perms()->sync($op_perm_ids);

            $rec_except = ['用户','角色','权限','权限类型','用户管理','基础数据','费用管理'];
            $rec_perm_cats = $cats->filter(function ($v)use($rec_except){
                return in_array($v->name,$rec_except)==false;
            });
            $rec_perm_ids = $rec_perm_cats->map(function($cat){
                return $cat->permissions->pluck('id');
            })->flatten()->all();
        }

        $role_rec = Role::query()->where('name','记录员')->first();
        if($role_rec){
            $role_rec->perms()->sync($rec_perm_ids);
        }

        $this->info('重新分配完毕');
    }
}
